//
//  GEMemento.m
//  GEMemento
//
//  Created by Grass on 15/8/12.
//  Copyright (c) 2015年 OFashioin. All rights reserved.
//

#import "GEMemento.h"

static inline NSString *mementoArchiverPath() {
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"memento.archiver"];
}

@implementation GEMemento

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.title      forKey:@"title"];
    [aCoder encodeObject:self.subTitle   forKey:@"subtitle"];
    [aCoder encodeObject:self.content    forKey:@"content"];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        if (aDecoder == nil) {
            return self;
        }
        self.title      = [aDecoder decodeObjectForKey:@"title"];
        self.subTitle   = [aDecoder decodeObjectForKey:@"subtitle"];
        self.content    = [aDecoder decodeObjectForKey:@"content"];
    }
    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<%@ : %p> %@", NSStringFromClass([self class]), self, @{@"title"    : self.title,
                                                                                                @"subTitle" : self.subTitle,
                                                                                                @"content"  : self.content}];
}

@end


@implementation GEMemento (Archive)

+ (GEMemento *)unarchiverMemento {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:mementoArchiverPath()];
}

+ (BOOL)archiverMememnto:(GEMemento *)memento {
    if (!memento) {
        return NO;

    }
    
    NSAssert([memento conformsToProtocol:@protocol(NSCoding)], @"没有遵守NSCoding协议");
    BOOL succeeded = [NSKeyedArchiver archiveRootObject:memento toFile:mementoArchiverPath()];
    return succeeded;
}

+ (BOOL)clearArchiverMemento {
    NSFileManager *fileManger = [NSFileManager defaultManager];
    return [fileManger removeItemAtPath:mementoArchiverPath() error:NULL];
}

@end

